package com.mm.cloth.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.mm.cloth.R;
import com.mm.cloth.view.MattingCanvasView;
import com.mm.cloth.view.SlideCompareView;
import com.mm.cloth.rmbg.MODNetProcessor;




import java.io.IOException;
import java.io.InputStream;

public class CanvasMattingActivity extends AppCompatActivity {
    private static final String TAG = "CanvasMattingActivity";
    private static final int REQUEST_IMAGE_PICK = 1001;
    private static final int REQUEST_PERMISSION = 1002;

    // 界面模式
    private enum ViewMode {
        EDIT,      // 编辑模式
        COMPARE    // 对比模式
    }

    private ViewMode currentMode = ViewMode.EDIT;
    
    private MattingCanvasView mattingCanvas;
    private SlideCompareView slideCompareView;
    private ImageView ivPreview;
    private Button btnSelectImage;
    private Button btnAutoMatting;
    private Button btnSaveResult;
    private ImageView btnBack;
    private Button btnBrushKeep;
    private Button btnBrushErase;
    private SeekBar seekBarBrushSize;
    
    private Bitmap originalBitmap;
    private Bitmap currentResultBitmap;
    private MODNetProcessor modNetProcessor;

    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_canvas_matting);
        
        initViews();
        setupListeners();
        checkPermissions();
    }
    
    private void initViews() {
        mattingCanvas = findViewById(R.id.mattingCanvas);
        slideCompareView = findViewById(R.id.slideCompareView);
        ivPreview = findViewById(R.id.ivPreview);
        btnSelectImage = findViewById(R.id.btnSelectImage);
        btnAutoMatting = findViewById(R.id.btnAutoMatting);
        btnSaveResult = findViewById(R.id.btnSaveResult);
        btnBack = findViewById(R.id.btnBack);
        btnBrushKeep = findViewById(R.id.btnBrushKeep);
        btnBrushErase = findViewById(R.id.btnBrushErase);
        seekBarBrushSize = findViewById(R.id.seekBarBrushSize);



        // 调试日志：检查按钮是否找到
        Log.d(TAG, "按钮初始化状态：");
        Log.d(TAG, "  btnAutoMatting: " + (btnAutoMatting != null ? "找到" : "未找到"));
        Log.d(TAG, "  btnSaveResult: " + (btnSaveResult != null ? "找到" : "未找到"));

        // 初始化按钮状态
        if (btnAutoMatting != null) {
            btnAutoMatting.setEnabled(false);
            Log.d(TAG, "  btnAutoMatting 设置为禁用状态");
        }
        if (btnSaveResult != null) {
            btnSaveResult.setEnabled(false);
            Log.d(TAG, "  btnSaveResult 设置为禁用状态");
        }
    }
    
    private void setupListeners() {
        Log.d(TAG, "设置按钮监听器");

        btnBack.setOnClickListener(v -> handleBackPress());

        // 画笔模式控制
        setupBrushControls();
        btnSelectImage.setOnClickListener(v -> selectImage());

        // 添加长按测试功能
        btnSelectImage.setOnLongClickListener(v -> {
            Log.d(TAG, "长按选择图片按钮，强制启用AI抠图按钮进行测试");
            if (btnAutoMatting != null) {
                btnAutoMatting.setEnabled(true);
                Toast.makeText(this, "已强制启用AI抠图按钮（测试）", Toast.LENGTH_SHORT).show();
            }
            return true;
        });

        if (btnAutoMatting != null) {
            btnAutoMatting.setOnClickListener(v -> {
                Log.d(TAG, "RMBG-2.0背景移除按钮被点击");
                performRMBGBackgroundRemoval();
            });
            Log.d(TAG, "  btnAutoMatting 监听器已设置");
        } else {
            Log.e(TAG, "  错误：btnAutoMatting 为 null，无法设置监听器");
        }

        if (btnSaveResult != null) {
            btnSaveResult.setOnClickListener(v -> {
                Log.d(TAG, "保存结果按钮被点击");
                saveCurrentResult();
            });
            Log.d(TAG, "  btnSaveResult 监听器已设置");
        } else {
            Log.e(TAG, "  错误：btnSaveResult 为 null，无法设置监听器");
        }

        // 异步初始化MODNet处理器
        initMODNetProcessor();
    }



    /**
     * 异步初始化MODNet处理器
     */
    private void initMODNetProcessor() {
        Log.d(TAG, "开始异步初始化MODNet处理器...");

        new Thread(() -> {
            try {
                modNetProcessor = new MODNetProcessor(this);

                if (!isFinishing() && !isDestroyed()) {
                    runOnUiThread(() -> {
                        try {
                            if (isFinishing() || isDestroyed()) {
                                Log.w(TAG, "Activity已销毁，跳过MODNet初始化UI更新");
                                return;
                            }

                            if (modNetProcessor.isInitialized()) {
                                Log.d(TAG, "MODNet处理器初始化成功");
                                Toast.makeText(this, "MODNet模型加载成功", Toast.LENGTH_SHORT).show();

                                // 启用抠图按钮
                                if (btnAutoMatting != null && originalBitmap != null) {
                                    btnAutoMatting.setEnabled(true);
                                }
                            } else {
                                Log.e(TAG, "MODNet处理器初始化失败");
                                Toast.makeText(this, "MODNet模型加载失败", Toast.LENGTH_SHORT).show();
                                modNetProcessor = null;
                            }
                        } catch (Exception uiException) {
                            Log.e(TAG, "MODNet初始化UI更新异常", uiException);
                        }
                    });
                }

            } catch (Exception e) {
                Log.e(TAG, "MODNet处理器初始化异常", e);
                if (!isFinishing() && !isDestroyed()) {
                    runOnUiThread(() -> {
                        try {
                            Toast.makeText(this, "MODNet模型加载异常：" + e.getMessage(), Toast.LENGTH_LONG).show();
                            modNetProcessor = null;
                        } catch (Exception uiException) {
                            Log.e(TAG, "MODNet异常处理UI更新失败", uiException);
                        }
                    });
                }
            }
        }).start();
    }

    /**
     * 设置画笔控制
     */
    private void setupBrushControls() {
        // 画笔模式切换
        btnBrushKeep.setOnClickListener(v -> {
            mattingCanvas.setBrushMode(false); // false = 保留模式
            updateBrushModeUI(false);
            Toast.makeText(this, "🖌️ 保留模式：涂抹要保留的区域", Toast.LENGTH_SHORT).show();
        });

        btnBrushErase.setOnClickListener(v -> {
            mattingCanvas.setBrushMode(true); // true = 擦除模式
            updateBrushModeUI(true);
            Toast.makeText(this, "🗑️ 擦除模式：涂抹要去除的区域", Toast.LENGTH_SHORT).show();
        });

        // 画笔大小调节
        seekBarBrushSize.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    // 将进度转换为画笔大小（10-60像素）
                    int brushSize = Math.max(10, progress + 10);
                    mattingCanvas.setBrushSize(brushSize);
                    Log.d(TAG, "画笔大小设置为: " + brushSize);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {}
        });

        // 初始化画笔状态
        mattingCanvas.setBrushMode(true); // 默认擦除模式（更符合用户直觉）
        mattingCanvas.setBrushSize(30); // 默认画笔大小
        updateBrushModeUI(true);
    }

    /**
     * 更新画笔模式UI
     */
    private void updateBrushModeUI(boolean isEraseMode) {
        if (isEraseMode) {
            // 擦除模式
            btnBrushErase.setTextColor(getResources().getColor(android.R.color.white));
            btnBrushErase.setBackgroundResource(R.drawable.btn_fairy_primary);
            btnBrushKeep.setTextColor(getResources().getColor(android.R.color.darker_gray));
            btnBrushKeep.setBackgroundResource(R.drawable.btn_fairy_outline);
        } else {
            // 保留模式
            btnBrushKeep.setTextColor(getResources().getColor(android.R.color.white));
            btnBrushKeep.setBackgroundResource(R.drawable.btn_fairy_primary);
            btnBrushErase.setTextColor(getResources().getColor(android.R.color.darker_gray));
            btnBrushErase.setBackgroundResource(R.drawable.btn_fairy_outline);
        }
    }

    /**
     * 切换界面模式
     */
    private void switchToMode(ViewMode mode) {
        currentMode = mode;

        // 隐藏所有视图
        mattingCanvas.setVisibility(View.GONE);
        slideCompareView.setVisibility(View.GONE);

        switch (mode) {
            case EDIT:
                mattingCanvas.setVisibility(View.VISIBLE);
                break;

            case COMPARE:
                slideCompareView.setVisibility(View.VISIBLE);
                break;
        }
    }

    /**
     * 处理返回按钮点击
     */
    private void handleBackPress() {
        switch (currentMode) {
            case COMPARE:
                // 从对比模式返回编辑模式，显示原图
                switchToMode(ViewMode.EDIT);
                if (originalBitmap != null) {
                    mattingCanvas.setImageBitmap(originalBitmap);
                }
                Toast.makeText(this, "返回编辑模式，可继续选择图片或抠图", Toast.LENGTH_SHORT).show();
                break;

            case EDIT:
            default:
                // 从编辑模式退出应用
                finish();
                break;
        }
    }

    /**
     * 初始化轻量级处理器（备用方案）
     */
//    private void initLightweightProcessor() {
//        Log.d(TAG, "初始化轻量级背景移除处理器...");
//
//        try {
////            lightweightProcessor = new LightweightRMBGProcessor(this);
//
//            if (lightweightProcessor.isInitialized()) {
//                Log.d(TAG, "轻量级处理器初始化成功");
//                Toast.makeText(this, "轻量级背景移除已就绪（基于算法的备用方案）", Toast.LENGTH_LONG).show();
//
//                // 启用抠图按钮
//                if (btnAutoMatting != null && originalBitmap != null) {
//                    btnAutoMatting.setEnabled(true);
//                }
//            } else {
//                Log.e(TAG, "轻量级处理器初始化失败");
//                Toast.makeText(this, "背景移除功能不可用", Toast.LENGTH_SHORT).show();
//            }
//
//        } catch (Exception e) {
//            Log.e(TAG, "轻量级处理器初始化异常", e);
//            Toast.makeText(this, "背景移除功能初始化失败", Toast.LENGTH_SHORT).show();
//        }
//    }

    /**
     * 执行RMBG-2.0背景移除
     */
    private void performRMBGBackgroundRemoval() {
        if (originalBitmap == null) {
            Toast.makeText(this, "请先选择图片", Toast.LENGTH_SHORT).show();
            return;
        }

        Log.d(TAG, "=== 开始AI抠图处理 ===");

        // 禁用按钮，防止重复点击
        btnAutoMatting.setEnabled(false);
        btnSaveResult.setEnabled(false);

        // 检查是否有手动绘制的遮罩
        boolean hasManualMask = mattingCanvas.hasDrawnPaths();

        if (hasManualMask) {
            Log.d(TAG, "检测到手动遮罩，使用手动遮罩进行抠图");
            performManualMaskMatting();
        } else {
            Log.d(TAG, "没有手动遮罩，使用自动MODNet背景移除");
            // 检查处理器状态
            if (modNetProcessor != null && modNetProcessor.isInitialized()) {
                performMODNetBackgroundRemoval();
            } else {
                Log.e(TAG, "MODNet处理器不可用");
                Toast.makeText(this, "MODNet背景移除功能不可用，请检查modnet.onnx模型文件", Toast.LENGTH_LONG).show();
                btnAutoMatting.setEnabled(true);
                return;
            }
        }
    }

    /**
     * 执行手动遮罩抠图
     */
    private void performManualMaskMatting() {
        Log.d(TAG, "=== 开始手动遮罩抠图处理 ===");

        new Thread(() -> {
            try {
                // 获取手动绘制的遮罩
                Bitmap maskBitmap = mattingCanvas.getMaskBitmap();
                if (maskBitmap == null) {
                    Log.e(TAG, "获取遮罩失败");
                    runOnUiThread(() -> {
                        btnAutoMatting.setEnabled(true);
                        Toast.makeText(this, "获取遮罩失败", Toast.LENGTH_SHORT).show();
                    });
                    return;
                }

                Log.d(TAG, "遮罩获取成功，开始应用遮罩");
                Log.d(TAG, "绘制路径数量: " + mattingCanvas.getPathHistorySize());

                // 保存遮罩用于调试（可选）
                saveMaskForDebug(maskBitmap);

                // 应用遮罩到原图
                Bitmap resultBitmap = applyMaskToImage(originalBitmap, maskBitmap);

                if (resultBitmap != null) {
                    Log.d(TAG, "手动遮罩抠图成功");

                    runOnUiThread(() -> {
                        try {
                            if (!isFinishing() && !isDestroyed()) {
                                // 保存结果
                                currentResultBitmap = resultBitmap;

                                // 设置对比视图
                                slideCompareView.setOriginalBitmap(originalBitmap);
                                slideCompareView.setProcessedBitmap(resultBitmap);

                                // 切换到对比模式
                                switchToMode(ViewMode.COMPARE);

                                // 启用按钮
                                if (btnAutoMatting != null) {
                                    btnAutoMatting.setEnabled(true);
                                }
                                if (btnSaveResult != null) {
                                    btnSaveResult.setEnabled(true);
                                }

                                Log.d(TAG, "=== 手动遮罩抠图处理完成 ===");
                                Toast.makeText(this, "手动遮罩抠图完成！滑动查看对比效果", Toast.LENGTH_LONG).show();
                            }
                        } catch (Exception e) {
                            Log.e(TAG, "UI更新异常", e);
                        }
                    });
                } else {
                    Log.e(TAG, "手动遮罩抠图失败");
                    runOnUiThread(() -> {
                        btnAutoMatting.setEnabled(true);
                        Toast.makeText(this, "手动遮罩抠图失败", Toast.LENGTH_SHORT).show();
                    });
                }

            } catch (Exception e) {
                Log.e(TAG, "手动遮罩抠图异常", e);
                runOnUiThread(() -> {
                    btnAutoMatting.setEnabled(true);
                    Toast.makeText(this, "手动遮罩抠图异常：" + e.getMessage(), Toast.LENGTH_SHORT).show();
                });
            }
        }).start();
    }

    /**
     * 应用遮罩到图像
     * @param originalImage 原始图像
     * @param maskImage 遮罩图像（白色保留，黑色移除）
     * @return 抠图结果
     */
    private Bitmap applyMaskToImage(Bitmap originalImage, Bitmap maskImage) {
        if (originalImage == null || maskImage == null) {
            Log.e(TAG, "原始图像或遮罩为空");
            return null;
        }

        try {
            // 创建结果图像
            Bitmap result = Bitmap.createBitmap(originalImage.getWidth(), originalImage.getHeight(), Bitmap.Config.ARGB_8888);

            // 获取像素数据
            int width = originalImage.getWidth();
            int height = originalImage.getHeight();
            int[] originalPixels = new int[width * height];
            int[] maskPixels = new int[width * height];
            int[] resultPixels = new int[width * height];

            originalImage.getPixels(originalPixels, 0, width, 0, 0, width, height);

            // 调整遮罩尺寸（如果需要）
            Bitmap resizedMask = maskImage;
            if (maskImage.getWidth() != width || maskImage.getHeight() != height) {
                resizedMask = Bitmap.createScaledBitmap(maskImage, width, height, true);
            }
            resizedMask.getPixels(maskPixels, 0, width, 0, 0, width, height);

            // 应用遮罩
            for (int i = 0; i < originalPixels.length; i++) {
                int originalPixel = originalPixels[i];
                int maskPixel = maskPixels[i];

                // 获取遮罩的亮度（白色=保留，黑色=移除）
                int maskBrightness = Color.red(maskPixel); // 使用红色通道作为亮度

                if (maskBrightness > 128) {
                    // 白色区域：保留原像素
                    resultPixels[i] = originalPixel;
                } else {
                    // 黑色区域：设置为透明
                    resultPixels[i] = Color.TRANSPARENT;
                }
            }

            // 设置结果像素
            result.setPixels(resultPixels, 0, width, 0, 0, width, height);

            // 清理临时资源
            if (resizedMask != maskImage) {
                resizedMask.recycle();
            }

            Log.d(TAG, "遮罩应用完成，结果尺寸: " + result.getWidth() + "x" + result.getHeight());
            return result;

        } catch (Exception e) {
            Log.e(TAG, "应用遮罩失败", e);
            return null;
        }
    }

    /**
     * 保存遮罩用于调试
     */
    private void saveMaskForDebug(Bitmap maskBitmap) {
        try {
            // 统计遮罩像素
            int[] pixels = new int[maskBitmap.getWidth() * maskBitmap.getHeight()];
            maskBitmap.getPixels(pixels, 0, maskBitmap.getWidth(), 0, 0, maskBitmap.getWidth(), maskBitmap.getHeight());

            int whitePixels = 0;
            int blackPixels = 0;
            int grayPixels = 0;

            for (int pixel : pixels) {
                int brightness = Color.red(pixel);
                if (brightness > 200) {
                    whitePixels++;
                } else if (brightness < 50) {
                    blackPixels++;
                } else {
                    grayPixels++;
                }
            }

            Log.d(TAG, "遮罩像素统计 - 白色(保留): " + whitePixels + ", 黑色(移除): " + blackPixels + ", 灰色: " + grayPixels);
            Log.d(TAG, "遮罩尺寸: " + maskBitmap.getWidth() + "x" + maskBitmap.getHeight());

        } catch (Exception e) {
            Log.e(TAG, "遮罩调试失败", e);
        }
    }

    /**
     * 执行MODNet ONNX背景移除
     */
    private void performMODNetBackgroundRemoval() {
        Log.d(TAG, "使用MODNet ONNX进行背景移除");
        Toast.makeText(this, "正在使用MODNet ONNX进行背景移除，请稍候...", Toast.LENGTH_SHORT).show();

        // 异步执行背景移除
        new Thread(() -> {
            try {
                Bitmap resultBitmap = modNetProcessor.removeBackground(originalBitmap);

                if (resultBitmap == null) {
                    Log.e(TAG, "MODNet ONNX背景移除失败");
                    runOnUiThread(() -> {
                        btnAutoMatting.setEnabled(true);
                        Toast.makeText(this, "MODNet背景移除失败，请检查模型文件", Toast.LENGTH_LONG).show();
                    });
                    return;
                }

                // 在主线程更新UI，添加安全检查
                if (!isFinishing() && !isDestroyed()) {
                    runOnUiThread(() -> {
                        try {
                            if (isFinishing() || isDestroyed()) {
                                Log.w(TAG, "Activity已销毁，跳过UI更新");
                                return;
                            }

                            Bitmap finalResult = resultBitmap;
                            Log.d(TAG, "MODNet ONNX背景移除成功：宽度=" + finalResult.getWidth() + ", 高度=" + finalResult.getHeight());

                            // 保存结果
                            currentResultBitmap = finalResult;

                            // 安全地设置对比视图的图片
                            if (slideCompareView != null && originalBitmap != null) {
                                slideCompareView.setOriginalBitmap(originalBitmap);
                                slideCompareView.setProcessedBitmap(finalResult);

                                // 切换到对比模式
                                switchToMode(ViewMode.COMPARE);
                            }

                            // 检查透明度
                            boolean hasTransparency = checkBitmapTransparency(finalResult);

                            // 启用按钮
                            if (btnAutoMatting != null) {
                                btnAutoMatting.setEnabled(true);
                            }
                            if (btnSaveResult != null) {
                                btnSaveResult.setEnabled(true);
                            }

                            // 显示完成消息
                            String message = hasTransparency ?
                                "MODNet抠图完成！滑动查看对比效果\n推理耗时: " + String.format("%.0f", modNetProcessor.inferenceTime()) + "ms" :
                                "MODNet抠图完成！滑动查看对比效果\n推理耗时: " + String.format("%.0f", modNetProcessor.inferenceTime()) + "ms";

                            Toast.makeText(this, message, Toast.LENGTH_LONG).show();

                            Log.d(TAG, "=== MODNet ONNX背景移除处理完成 ===");

                        } catch (Exception e) {
                            Log.e(TAG, "UI更新异常", e);
                        }
                    });
                }

            } catch (Exception e) {
                Log.e(TAG, "MODNet ONNX背景移除异常", e);
                if (!isFinishing() && !isDestroyed()) {
                    runOnUiThread(() -> {
                        try {
                            if (btnAutoMatting != null) {
                                btnAutoMatting.setEnabled(true);
                            }
                            Toast.makeText(this, "MODNet背景移除异常：" + e.getMessage(), Toast.LENGTH_LONG).show();
                        } catch (Exception uiException) {
                            Log.e(TAG, "UI异常处理失败", uiException);
                        }
                    });
                }
            }
        }).start();
    }

    private void checkPermissions() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    REQUEST_PERMISSION);
        }
    }
    
    private void selectImage() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");
        startActivityForResult(intent, REQUEST_IMAGE_PICK);
    }
    



    private static class TransparencyCheckResult {
        boolean hasTransparency;
        int transparentPixels;
        int totalChecked;

        TransparencyCheckResult(boolean hasTransparency, int transparentPixels, int totalChecked) {
            this.hasTransparency = hasTransparency;
            this.transparentPixels = transparentPixels;
            this.totalChecked = totalChecked;
        }
    }

    private TransparencyCheckResult checkBitmapTransparencyDetailed(Bitmap bitmap) {
        if (bitmap == null) return new TransparencyCheckResult(false, 0, 0);

        // 检查图片是否有透明像素
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int transparentPixels = 0;
        int totalChecked = 0;

        // 使用更密集的采样来确保不遗漏透明区域
        for (int x = 0; x < width; x += 5) { // 每5像素采样一次，提高检测精度
            for (int y = 0; y < height; y += 5) {
                int pixel = bitmap.getPixel(x, y);
                int alpha = (pixel >> 24) & 0xff;
                totalChecked++;

                if (alpha < 255) { // 发现透明或半透明像素
                    transparentPixels++;
                }
            }
        }

        boolean hasTransparency = transparentPixels > 0;
        return new TransparencyCheckResult(hasTransparency, transparentPixels, totalChecked);
    }

    private boolean checkBitmapTransparency(Bitmap bitmap) {
        return checkBitmapTransparencyDetailed(bitmap).hasTransparency;
    }

    /**
     * 保存图片到相册
     */
    private void saveImageToGallery(Bitmap bitmap) {
        try {
            String savedImageURL = MediaStore.Images.Media.insertImage(
                getContentResolver(),
                bitmap,
                "GPU_Matting_" + System.currentTimeMillis(),
                "GPU加速抠图结果"
            );

            if (savedImageURL != null) {
                Log.d(TAG, "图片保存成功：" + savedImageURL);
                Toast.makeText(this, "图片已保存到相册", Toast.LENGTH_SHORT).show();
            } else {
                Log.e(TAG, "图片保存失败");
                Toast.makeText(this, "图片保存失败", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Log.e(TAG, "保存图片异常", e);
            Toast.makeText(this, "保存失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        if (requestCode == REQUEST_IMAGE_PICK && resultCode == RESULT_OK && data != null) {
            Uri imageUri = data.getData();
            if (imageUri != null) {
                try {
                    InputStream inputStream = getContentResolver().openInputStream(imageUri);
                    Bitmap tempBitmap = BitmapFactory.decodeStream(inputStream);

                    if (tempBitmap != null) {
                        Log.d(TAG, "原始图片尺寸：" + tempBitmap.getWidth() + "x" + tempBitmap.getHeight());

                        // 检查并压缩大图片以避免内存问题
                        originalBitmap = compressBitmapIfNeeded(tempBitmap);

                        // 释放临时bitmap
                        if (originalBitmap != tempBitmap) {
                            tempBitmap.recycle();
                        }

                        // 确保切换到编辑模式并显示新图片
                        switchToMode(ViewMode.EDIT);
                        mattingCanvas.setImageBitmap(originalBitmap);

                        Log.d(TAG, "图片加载成功，开始启用按钮");
                        Log.d(TAG, "  处理后尺寸：" + originalBitmap.getWidth() + "x" + originalBitmap.getHeight());

                        // 重置按钮状态
                        if (btnAutoMatting != null) {
                            btnAutoMatting.setEnabled(modNetProcessor != null && modNetProcessor.isInitialized());
                        }
                        if (btnSaveResult != null) {
                            btnSaveResult.setEnabled(false);
                        }

                        // 清理之前的结果
                        currentResultBitmap = null;

                        Toast.makeText(this, "图片加载成功，点击按钮即可一键AI抠图", Toast.LENGTH_SHORT).show();
                    } else {
                        Log.e(TAG, "错误：图片加载失败，originalBitmap 为 null");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(this, "图片加载失败", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
    
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        
        if (requestCode == REQUEST_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "权限已授予", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "需要存储权限才能选择图片", Toast.LENGTH_SHORT).show();
            }
        }
    }
    




    /**
     * 压缩图片以避免内存问题
     */
    private Bitmap compressBitmapIfNeeded(Bitmap bitmap) {
        if (bitmap == null) return null;

        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        // 设置最大尺寸限制（避免内存溢出）
        final int MAX_SIZE = 2048;

        if (width <= MAX_SIZE && height <= MAX_SIZE) {
            Log.d(TAG, "图片尺寸合适，无需压缩");
            return bitmap;
        }

        // 计算压缩比例
        float scale = Math.min((float) MAX_SIZE / width, (float) MAX_SIZE / height);
        int newWidth = (int) (width * scale);
        int newHeight = (int) (height * scale);

        Log.d(TAG, "压缩图片：" + width + "x" + height + " -> " + newWidth + "x" + newHeight);

        try {
            Bitmap compressedBitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
            return compressedBitmap;
        } catch (OutOfMemoryError e) {
            Log.e(TAG, "压缩图片时内存不足", e);
            System.gc();
            return bitmap; // 返回原图片
        }
    }

    /**
     * 保存当前结果
     */
    private void saveCurrentResult() {
        if (currentResultBitmap == null) {
            Toast.makeText(this, "没有可保存的抠图结果", Toast.LENGTH_SHORT).show();
            return;
        }

        Log.d(TAG, "保存本地抠图结果");
        saveImageToGallery(currentResultBitmap);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

    @Override
    protected void onDestroy() {
        Log.d(TAG, "Activity正在销毁，释放资源...");
        super.onDestroy();

        try {
            // 释放MODNet处理器资源
            if (modNetProcessor != null) {
                modNetProcessor.release();
                modNetProcessor = null;
            }

            // 释放图片资源
            if (originalBitmap != null && !originalBitmap.isRecycled()) {
                originalBitmap.recycle();
                originalBitmap = null;
            }

            if (currentResultBitmap != null && !currentResultBitmap.isRecycled()) {
                currentResultBitmap.recycle();
                currentResultBitmap = null;
            }

            // 强制垃圾回收
            System.gc();

        } catch (Exception e) {
            Log.e(TAG, "释放Activity资源时出错", e);
        }

        Log.d(TAG, "Activity销毁完成");
    }
}
